﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Objects;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

using WatiN.Core;
using WebAuto.DataModel;
using WebAutoUtils;
using WebAutomation;
using WebAutomation.Browsers;
using Form = System.Windows.Forms.Form;
using MessageBox = System.Windows.MessageBox;
using System.Diagnostics;
using Application = System.Windows.Forms.Application;

namespace WebAuto
{
    public partial class Form1 : Form
    {
        public string _testLines = "";
        private TestDebug testDebugForm;

        public List<Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>> TestResultsList= new List<Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>>();
        public List<Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>> TestResultsOfTest = new List<Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>>();
        public Dictionary<int, Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>> FullResultsOfTests = new Dictionary<int, Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>>();
        public Dictionary<string, string> ListOfTestsToRun = new Dictionary<string, string>();
        public string CurrentTestRunning = "";
        public string CurrentTestLocationRunning = "";
        private const int CP_NOCLOSE_BUTTON = 0x200;
        private Data _data;

        
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams myCp = base.CreateParams;
                myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
                return myCp;
            }
        } 

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _data = new Data();
            string startFolderDirectory = Environment.CurrentDirectory;
            if (!startFolderDirectory.ToLower().Contains(@"\bin\debug"))
            {
                txtFolderName.Text = startFolderDirectory + @"\Tests";
            }
            string defaultTestsLocation = "";
            _loadPersonalSettings(ref defaultTestsLocation);
            if (!string.IsNullOrEmpty(defaultTestsLocation))
            {
                txtFolderName.Text = defaultTestsLocation;
            }
            _populateChart();
            this.Text = "Bunny Chow-Integration Tester v"+Utils.GetVersionNumber();
        }

       


        
        private void _loadPersonalSettings(ref string defaultTestsLocation)
        {
            string settingsFile = System.Environment.CurrentDirectory + "\\Personal\\Settings.txt";
            try
            {
                if (File.Exists(settingsFile))
                {
                    string line = "";
                    using (StreamReader sr = new StreamReader(settingsFile))
                    {
                        while ((line = sr.ReadLine()) != null)
                        {
                            if (line.StartsWith("DefaultTestFolder"))
                            {
                                if (!string.IsNullOrEmpty(line.Split('|')[1]))
                                {
                                    defaultTestsLocation = line.Split('|')[1].Replace(";", "");
                                }
                            }
                        }

                    }

                }
            }catch(Exception ex)
            {
                
            }

        }



        private void btnRunTest_Click(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            

            runTest();
        }


        private string _getFirstCheckedTestToRun()
        {
            string returnValue = "";

            foreach (DataGridViewRow itemRow in dataGridView1.Rows)
            {
                bool canRun = itemRow.Cells[3].Value.ToString().ToLower() == "true";
                if (canRun)
                {
                    string fileName = itemRow.Cells[0].Value.ToString();
                    string fullFileName = txtFolderName.Text + "\\" + fileName;
                    returnValue= fullFileName;
                    break;
                }


            }

            return returnValue;
        }


        private void runTest()
        {
            string codeLines = "";
            _testLines = "~";
            int countToRun = 0;
            foreach(DataGridViewRow itemRow in dataGridView1.Rows)
            {
                bool canRun = itemRow.Cells[3].Value.ToString().ToLower()=="true";
                if(canRun)
                {
                    //itemRow.Cells[1].Value = "Running...";
                    string fileName = itemRow.Cells[0].Value.ToString();
                    string fullFileName = txtFolderName.Text + "\\" + fileName;
                    _testLines += "," + fullFileName;
                    if(!ListOfTestsToRun.ContainsKey(fileName))
                    {
                        ListOfTestsToRun.Add(fileName, fullFileName);
                    }
                    countToRun++;
                }
                

            }

            if (countToRun>1)
            {

                var result = MessageBox.Show("Are you sure you want to run more than one test?",
                                             "Confirm multiple test run", MessageBoxButton.YesNo);
                if(result==MessageBoxResult.No)
                {

                    return;
                }
            }

            _testLines = _testLines.Replace("~,", "").Replace("~", "");

            if (string.IsNullOrEmpty(_testLines) || ListOfTestsToRun.Count == 0)
            {
                MessageBox.Show("No test files have been selected to run!");
            }else
            {
                if (chkDebug.Checked == true)
                {
                    if (countToRun>1)
                    {
                        MessageBox.Show("You cannot debug more than one selected test!");
                        return;
                    }
                    string firstCheckedTestToRun = _getFirstCheckedTestToRun();
                    if (string.IsNullOrEmpty(firstCheckedTestToRun))
                    {
                        MessageBox.Show("Cannot get the single checked test!");
                        return;
                    }
                    testDebugForm = new TestDebug();
                    testDebugForm.PopulateDebugBox(firstCheckedTestToRun);
                    testDebugForm.Show();
                    
                }else
                {
                    lblTestStatus.Text = DateTime.Now.ToString() + "..Tests running...please wait...";
                    this.WindowState = FormWindowState.Minimized;
                    RunSelectedTests();
                }
                
            }
        }


        private void _setRowStatus(string testName)
        {
            foreach (DataGridViewRow itemRow in dataGridView1.Rows)
            {
                if(itemRow.Cells[0].Value.ToString()==testName)
                {
                    itemRow.Cells[1].Value = "Running..";
                    itemRow.Cells[0].Style.BackColor = Color.Wheat;
                    itemRow.Cells[1].Style.BackColor = Color.Wheat;
                    itemRow.Cells[2].Style.BackColor = Color.Wheat;
                    itemRow.Cells[3].Style.BackColor = Color.Wheat;
                    itemRow.Cells[4].Style.BackColor = Color.Wheat;
                    itemRow.Cells[5].Style.BackColor = Color.Wheat;
                    break;
                }
            }
        }


        private void _updateRowStatus(string testName, bool isFailed, bool isFrameworkErr, string errorMessage, string resultFolderLocation, string browser)
        {
            string status = "";
            string message = errorMessage;
            foreach (DataGridViewRow itemRow in dataGridView1.Rows)
            {
                if (itemRow.Cells[0].Value.ToString().ToLower() == testName.ToLower())
                {
                    if (isFrameworkErr)
                    {
                        status = "Error";
                        itemRow.Cells[1].Value = "Error";
                        itemRow.Cells[0].Style.BackColor = Color.Violet;
                        itemRow.Cells[1].Style.BackColor = Color.Violet;
                        itemRow.Cells[2].Style.BackColor = Color.Violet;
                        itemRow.Cells[3].Style.BackColor = Color.Violet;
                        itemRow.Cells[4].Style.BackColor = Color.Violet;
                        itemRow.Cells[4].Value = errorMessage;
                        itemRow.Cells[5].Style.BackColor = Color.Violet;
                    }
                    else
                    {
                        if (isFailed)
                        {
                            status = "Failed";
                            itemRow.Cells[1].Value = "Failed";
                            itemRow.Cells[0].Style.BackColor = Color.Red;
                            itemRow.Cells[1].Style.BackColor = Color.Red;
                            itemRow.Cells[2].Style.BackColor = Color.Red;
                            itemRow.Cells[3].Style.BackColor = Color.Red;
                            itemRow.Cells[4].Style.BackColor = Color.Red;
                            itemRow.Cells[4].Value = errorMessage;
                            itemRow.Cells[5].Style.BackColor = Color.Red;
                        }
                        else
                        {
                            status = "Passed";
                            itemRow.Cells[1].Value = "Passed";
                            itemRow.Cells[0].Style.BackColor = Color.GreenYellow;
                            itemRow.Cells[1].Style.BackColor = Color.GreenYellow;
                            itemRow.Cells[2].Style.BackColor = Color.GreenYellow;
                            itemRow.Cells[3].Style.BackColor = Color.GreenYellow;
                            itemRow.Cells[4].Style.BackColor = Color.GreenYellow;
                            itemRow.Cells[4].Value = errorMessage;
                            itemRow.Cells[5].Style.BackColor = Color.GreenYellow;
                        }
                    }
                    DateTime dateRun = DateTime.Now;
                    itemRow.Cells[2].Value = dateRun.ToString("dd MMM yyyy HH:mm:ss");
                    if (status == "Failed" || status == "Error")
                    {
                        resultFolderLocation = resultFolderLocation + "_Failed";
                    }
                    _data.SaveTestRun(testName, CurrentTestRunning, CurrentTestLocationRunning, dateRun, status, message, resultFolderLocation, browser);
                    break;
                }
            }
        }

        public void RunSelectedTests()
        {
            Dictionary<string, string> tmpList = ListOfTestsToRun;
            if (tmpList.Count > 0)
            {
                foreach (var item in tmpList)
                {
                    string fileName = item.Key;
                    string fileFullName = item.Value;
                    _setRowStatus(fileName);
                    CurrentTestRunning = fileName;
                    CurrentTestLocationRunning = fileFullName;
                    WebAutomation.WebAuto.TestConfiguration testConfiguration =new WebAutomation.WebAuto.TestConfiguration();
                    testConfiguration.DefaultBrowser = ConfigurationManager.AppSettings["DefaultBrowser"];
                    testConfiguration.DefaultStartURL = ConfigurationManager.AppSettings["DefaultStartURL"];
                    testConfiguration.DefaultEndOrFailURL = ConfigurationManager.AppSettings["DefaultEndURL"];
                    testConfiguration.DefaultTestRepo = ConfigurationManager.AppSettings["DefaultTestRepoLocation"];
                    testConfiguration.DefaultSQLConnection = ConfigurationManager.AppSettings["DefaultDatabaseConnection"];
                    testConfiguration.DefaultIterations = Convert.ToInt32(ConfigurationManager.AppSettings["DefaultIterations"]);
                    testConfiguration.DefaultRecordVideo = ConfigurationManager.AppSettings["DefaultRecordVideo"].ToLower() == "true" || ConfigurationManager.AppSettings["DefaultRecordVideo"].ToLower() == "yes" || ConfigurationManager.AppSettings["DefaultRecordVideo"].ToLower() == "1";

                    WebAutomation.WebAuto webAuto = new WebAutomation.WebAuto(fileFullName, testConfiguration);
                    webAuto.RunTest(onTestRunStart, onTestRunComplete, onTestCommandStart, null, false, null, General.GetExceptionRules());
                    ListOfTestsToRun.Remove(fileName);
                    break;
                }
            }else
            {
                //all completed
                _updateGridRowStatus(TestResultsList);
                _sendEmailOfResults();
              
                TestResultsList =
                    new List<Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>>();
                WebAutomation.WebAuto.TestId = 0;
                WebAutomation.TestCommands.DisposeVariables();
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void _updateGridRowStatus(List<Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>> testResults = null)
        {

            bool isFailed = false;
            string browser = "";
            string t = CurrentTestRunning;
            //var itemList = TestResultsOfTest[0].Where(i => i.Key.TestName == CurrentTestRunning || i.Key.TestFileName == CurrentTestRunning);
            //if (testResults != null)
            //{
            //    itemList = testResults[0].Where(i => i.Key.TestName == CurrentTestRunning || i.Key.TestFileName == CurrentTestRunning);
            //}
            foreach (var itemList in testResults)
            {
                string testName = "";
                if (itemList.Count() > 0)
                {

                    foreach (var items in itemList)
                    {
                        browser = items.Key.TestBrowser;
                        testName = items.Key.TestFileName;
                        var list = items.Value;
                        var secToRun = 0.00;
                        var name = "";
                        var tmpName = "";
                        foreach (var listItem in list.Where(i => i.Key > -1))
                        {
                            foreach (var val in listItem.Value)
                            {
                                isFailed = !val.LinePassed;

                                if (isFailed)
                                {

                                    break;
                                }

                            }

                            if (isFailed)
                            {

                                break;
                            }

                        }

                        if (isFailed)
                        {

                            break;
                        }

                    }

                    bool isFrameworkErr = false;
                    string errorMessage = "";
                    string resultFolderLocation = "";
                    foreach (var items in itemList)
                    {
                        var list = items.Value;
                        var secToRun = 0.00;
                        var name = "";
                        var tmpName = "";
                        foreach (var listItem in list.Where(i => i.Key > -1))
                        {
                            foreach (var val in listItem.Value)
                            {
                                isFrameworkErr = val.IsFrameworkError;
                                errorMessage = val.LineMessage;
                                resultFolderLocation = val.ResultsFolderLocation;
                                if (isFrameworkErr)
                                {

                                    break;
                                }

                            }

                            if (isFrameworkErr)
                            {

                                break;
                            }

                        }

                        if (isFrameworkErr)
                        {

                            break;
                        }

                    }

                    _updateRowStatus(testName, isFailed, isFrameworkErr, errorMessage, resultFolderLocation, browser);
                   


                }
                

            }
            

        }



        private void onTestCommandStart(string[] param,int iLineCount,Thread thread,WebBrowserObject browserObject)
        {
           

        }


        private void onTestRunStart(Dictionary<int, string> TestLines, Thread thread)
        {
            CheckForIllegalCrossThreadCalls = false;



        }

        private void onTestRunComplete(Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>> TestResults, Thread thread)
        {
            CheckForIllegalCrossThreadCalls = false;
            lblTestStatus.Text = DateTime.Now.ToString() + "..Tests Completed.";
            List<Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>> tmpList =
                new List<Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>>();
            tmpList.Add(TestResults);
            TestResultsOfTest = tmpList;
            TestResultsList.Add(TestResults);
            int lastCount = FullResultsOfTests.Count();
            if (lastCount > 0)
            {
                lastCount++;
            }else
            {
                lastCount=1;
            }
            FullResultsOfTests.Add(lastCount, TestResults); 
            _drawTestCommandTimeChart();
            _mapTestStatusToGridRow();
            _setStatus();
            RunSelectedTests();
        }


        private void _sendEmailOfResults()
        {
            string emailTestStatus = "";
            string emailErrorMessage = "";
            int iCount = 0;
            List<DataObjects.TestDataResults> listOfTestDetails = new List<DataObjects.TestDataResults>();
            foreach (var items in TestResultsList)
            {
                bool isFailed = false;
                bool isFrameworkErr = false;
                string failErrorMessage = "";
                string frameworkErrorMessage = "";
                
                _testStatus(TestResultsList[iCount], ref isFailed, ref isFrameworkErr, ref failErrorMessage, ref frameworkErrorMessage);

                DataObjects.TestDataResults testDetails = new DataObjects.TestDataResults();
                var testData = TestResultsList[iCount];
                foreach (var data in testData)
                {
                    testDetails.TestName = data.Key.TestName;
                    testDetails.TestFileName = data.Key.TestFileName;
                    testDetails.TestDescription = data.Key.TestDescription;
                    testDetails.TestResultsFolder = data.Key.TestResultsFolder;
                    testDetails.TestBrowser = data.Key.TestBrowser;
                    testDetails.TestLogFolderLocation = data.Key.TestLogFolderLocation;
                    testDetails.IsFailed = isFailed;
                    testDetails.IsFrameworkErr = isFrameworkErr;
                    testDetails.FailErrorMessage = failErrorMessage;
                    testDetails.FrameworkErrorMessage = frameworkErrorMessage;
                    break;
                }
                listOfTestDetails.Add(testDetails);

                iCount++;
            }
            string errorEmail = "";
            General.SendEmail("BunnyChow-Integration Tester " + Utils.GetVersionNumber() + " Win form process", "BunnyChow Automation Results", listOfTestDetails, ref errorEmail);


        }


        private void _setStatus()
        {
            string emailTestStatus = "";
            string emailErrorMessage = "";
            int iCount = 0;
            foreach (var items in TestResultsOfTest)
            {
                bool isFailed = false;
                bool isFrameworkErr = false;
                string failErrorMessage = "";
                string frameworkErrorMessage = "";

                _testStatus(TestResultsOfTest[iCount], ref isFailed, ref isFrameworkErr, ref failErrorMessage, ref frameworkErrorMessage);
                
                iCount++;
            }



        }

        private void _testStatus(Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>> TestResults, ref bool isFailed, ref bool isFrameworkErr, ref string failErrorMessage, ref string frameworkErrorMessage)
        {
            foreach (var items in TestResults)
            {
                var list = items.Value;
                var secToRun = 0.00;
                var name = "";
                var tmpName = "";

                foreach (var listItem in list.Where(i => i.Key > -1))
                {
                    
                    foreach (var val in listItem.Value)
                    {
                        
                        isFailed = !val.LinePassed;
                        failErrorMessage = val.LineMessage;
                        if (isFailed)
                        {

                            break;
                        }

                    }

                    if (isFailed)
                    {

                        break;
                    }

                }

                if (isFailed)
                {

                    break;
                }

            }


            string errorMessage = "";
            foreach (var items in TestResults)
            {
                var list = items.Value;
                var secToRun = 0.00;
                var name = "";
                var tmpName = "";
                foreach (var listItem in list.Where(i => i.Key > -1))
                {
                    foreach (var val in listItem.Value)
                    {
                        isFrameworkErr = val.IsFrameworkError;
                        frameworkErrorMessage = val.LineMessage;
                        if (isFrameworkErr)
                        {

                            break;
                        }

                    }

                    if (isFrameworkErr)
                    {

                        break;
                    }

                }

                if (isFrameworkErr)
                {

                    break;
                }

            }

           

        }

        private void _mapTestStatusToGridRow(List<Dictionary<WebAutomation.WebAuto.TestData, Dictionary<int, List<TestLineResult>>>> testResults=null)
        {
           
            bool isFailed = false;
            string browser = "";
            var itemList = TestResultsOfTest[0].Where(i => i.Key.TestName == CurrentTestRunning || i.Key.TestFileName == CurrentTestRunning);
            if (testResults!=null)
            {
                itemList = testResults[0].Where(i => i.Key.TestName == CurrentTestRunning || i.Key.TestFileName == CurrentTestRunning);
            }
            if (itemList.Count() > 0)
            {

                foreach (var items in itemList)
                {
                    browser = items.Key.TestBrowser;
                    var list = items.Value;
                    var secToRun = 0.00;
                    var name = "";
                    var tmpName = "";
                    foreach (var listItem in list.Where(i => i.Key > -1))
                    {
                        foreach (var val in listItem.Value)
                        {
                            isFailed = !val.LinePassed;
                            
                            if (isFailed)
                            {

                                break;
                            }

                        }

                        if (isFailed)
                        {

                            break;
                        }

                    }

                    if (isFailed)
                    {

                        break;
                    }

                }

                bool isFrameworkErr = false;
                string errorMessage = "";
                string resultFolderLocation = "";
                foreach (var items in itemList)
                {
                    var list = items.Value;
                    var secToRun = 0.00;
                    var name = "";
                    var tmpName = "";
                    foreach (var listItem in list.Where(i => i.Key > -1))
                    {
                        foreach (var val in listItem.Value)
                        {
                            isFrameworkErr = val.IsFrameworkError;
                            errorMessage = val.LineMessage;
                            resultFolderLocation = val.ResultsFolderLocation;
                            if (isFrameworkErr)
                            {

                                break;
                            }

                        }

                        if (isFrameworkErr)
                        {

                            break;
                        }

                    }

                    if (isFrameworkErr)
                    {

                        break;
                    }

                }

                _updateRowStatus(CurrentTestRunning, isFailed, isFrameworkErr, errorMessage, resultFolderLocation, browser);
                _populateChart();


            }

        }



        private void _populateChart()
        {
            List<pr_GetTestRunStatusCount_Chart_Result> listOfTestRunStatusChart = _data.GetTestRunStatusCount_Chart("").ToList();

            ChartArea chartArea1 = new ChartArea("ChartArea1");
            //chartArea1.Area3DStyle.Enable3D = true;
            
            chTestCommandTime.Series.Clear();
            chTestCommandTime.ChartAreas.Clear();
            chTestCommandTime.ChartAreas.Add(chartArea1);
            //chTestCommandTime.Dock = DockStyle.;
            chTestCommandTime.Series.Add("Series1");
            chTestCommandTime.Series.Add("Series2");
            chTestCommandTime.Series.Add("Series3");
            
            
            foreach (var item in listOfTestRunStatusChart)
            {
                
                chTestCommandTime.Series[0].ChartType = SeriesChartType.StackedColumn;
                chTestCommandTime.Series[1].ChartType = SeriesChartType.StackedColumn;
                chTestCommandTime.Series[2].ChartType = SeriesChartType.StackedColumn;
                chTestCommandTime.Series[0].Color = Color.LawnGreen;
                chTestCommandTime.Series[1].Color = Color.Red;
                chTestCommandTime.Series[2].Color = Color.Violet;


                chTestCommandTime.Series[0].Points.AddXY(item.TestName, item.Passed);
                chTestCommandTime.Series[1].Points.AddXY(item.TestName, item.Failed);
                chTestCommandTime.Series[2].Points.AddXY(item.TestName, item.Error);

               



            }
            chartArea1.CursorX.IsUserEnabled = true; 
            chartArea1.CursorX.IsUserSelectionEnabled = true; 
            chartArea1.CursorY.IsUserEnabled = true; 
            chartArea1.CursorY.IsUserSelectionEnabled = true;

        }

        private void _drawTestCommandTimeChart()
        {

            
           // _populateTestCommandTimeChart(cboListofTests.Text);
            //cboListofTests.Visible = true;

        }

        
        //private void _populateTestCommandTimeChart(string testName)
        //{

        //    if (chTestCommandTime.Series.Count>0)
        //    {
        //        chTestCommandTime.Series.RemoveAt(0);
        //    }
        //    chTestCommandTime.Series.Add("Series1");
        //    chTestCommandTime.Series["Series1"].ChartType = SeriesChartType.Column;
        //    chTestCommandTime.ChartAreas[0].Area3DStyle.Enable3D = true;
        //    chTestCommandTime.ChartAreas[0].Area3DStyle.Rotation = 5;

        //    Dictionary<string, double> listofCommands = new Dictionary<string, double>();
        //    foreach (var items in TestResultsOfTest.Where(i => i.Key.TestName == testName))
        //    {
        //        var list = items.Value;
        //        var secToRun = 0.00;
        //        var name = "";
        //        var tmpName = "";
        //        foreach (var listItem in list.Where(i=>i.Key>-1))
        //        {

        //            //group.Sum(x => (x.EndTime-x.StartTime).Seconds
        //            var groupedList = listItem.Value.GroupBy(x => x.LineCommand);
        //            foreach (var item in groupedList)
        //            {
        //                name = item.FirstOrDefault().LineSubCommand+"-"+item.FirstOrDefault().LineCommand;
        //                secToRun += (item.FirstOrDefault().EndTime - item.FirstOrDefault().StartTime).TotalSeconds;
        //                if(!listofCommands.ContainsKey(name))
        //                {
        //                    listofCommands.Add(name, secToRun);
        //                }else
        //                {
        //                    listofCommands[name]= secToRun;
        //                }
        //                //chTestCommandTime.Series["Series1"].Points.AddXY(name, secToRun);
                        
        //            }                   

        //        }

        //    }

        //    foreach(var items in listofCommands)
        //    {
        //        chTestCommandTime.Series["Series1"].Points.AddXY(items.Key, items.Value);
        //    }
            

        //}

        private void cboListofTests_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

      

        private void btnLoadTests_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFolderName.Text))
            {
                chkSelectAllNone.Enabled = false;
                btnRunTest.Enabled = false;
                btnCreateEXE.Enabled = false;
                System.Windows.MessageBox.Show("Please enter a test folder path!");
            }
            else
            {
                if (!Directory.Exists(txtFolderName.Text))
                {
                    chkSelectAllNone.Enabled = false;
                    btnRunTest.Enabled = false;
                    btnCreateEXE.Enabled = false;
                    MessageBox.Show("The test folder path does not exist!");

                }
                else
                {
                    _loadTestsInGrid();
                    btnRunTest.Enabled = true;
                    chkSelectAllNone.Enabled = true;
                    btnCreateEXE.Enabled = true;
                    _savePersonalSettings();
                }


            }
        }

        private void _savePersonalSettings()
        {
            string settingsFile = System.Environment.CurrentDirectory + "\\Personal\\Settings.txt";
            try
            {
                if (File.Exists(settingsFile))
                {
                    string currentLines = "";
                    string newLines = "";
                    using (StreamReader sr = new StreamReader(settingsFile))
                    {
                        while ((currentLines = sr.ReadLine()) != null)
                        {
                            if (currentLines.StartsWith("DefaultTestFolder"))
                            {
                                currentLines = "DefaultTestFolder|" + txtFolderName.Text + ";";
                            }
                            newLines += currentLines;
                        }

                    }

                    FileInfo fi = new FileInfo(settingsFile);
                    using (TextWriter tw = new StreamWriter(fi.Open(FileMode.Truncate)))
                    {
                        tw.Write(newLines);
                    }

                }
            }
            catch (Exception ex)
            {

            }


        }




        private void _loadTestsInGrid()
        {
            dataGridView1.Rows.Clear();
            dataGridView1.ReadOnly = false;
            string[] files = Directory.GetFiles(txtFolderName.Text);
            foreach(var item in files)
            {
                FileInfo fi = new FileInfo(item);
                if (fi.Extension == ".txt")
                {
                    string browser = TestFileReader.GetTestData(item).TestBrowser;
                    string testFileName = fi.Name;
                    dataGridView1.Rows.Add(testFileName, "", "", true, "", browser);
                }

            }


            foreach(DataGridViewRow itemRow in dataGridView1.Rows)
            {
                itemRow.Cells[1].Value = "Waiting...";
                itemRow.Cells[0].Style.BackColor = Color.White;
                itemRow.Cells[1].Style.BackColor = Color.White;
                itemRow.Cells[2].Style.BackColor = Color.White;
                itemRow.Cells[3].Style.BackColor = Color.White;
                itemRow.Cells[4].Style.BackColor = Color.White;
                itemRow.Cells[5].Style.BackColor = Color.White;

            }

        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.SelectedCells.Count > 0)
            {
                DataGridViewSelectedCellCollection col = this.dataGridView1.SelectedCells;
                var selectedTestName = col[0].Value;
                string fullFileName = txtFolderName.Text + "\\" + selectedTestName;
                var testData = TestFileReader.GetTestData(fullFileName);
                testData.TestFileName = fullFileName;
                TestHistoryResults testHistoryFrm = new TestHistoryResults();
                testHistoryFrm.Init(testData);
                testHistoryFrm.ShowDialog();

                //ProcessStartInfo startInfo = new ProcessStartInfo("notepad.exe");
                //startInfo.Arguments = fullFileName;
                //Process.Start(startInfo);
            }
        }

        private void btnRecordtest_Click(object sender, EventArgs e)
        {
            IERecorder frm = new IERecorder();
            frm.ShowDialog();
            //TestRecorder.frmMain frm = new frmMain();
           // frm.ShowDialog();

        }

        private void button1_Click(object sender, EventArgs e)
        {
             //WebAutomation.WebAuto webAuto = new WebAutomation.WebAuto();
             //webAuto.BrowserObject = new IE("http://www.google.co.za");

            // TextBoxCommand txt = new TextBoxCommand(webAuto.BrowserObject);
            // TextField txtField=txt.GetTextBox("q");
            // txt.TypeText("cat", txtField);

            //ButtonCommand btn = new ButtonCommand(webAuto.BrowserObject);
            //WatiN.Core.Button btnField = btn.GetButton("btnG");
            //btn.ButtonClick(btnField);
            

        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if(lblTestStatus.Text.Contains("running"))
            {
                MessageBox.Show("You cannot exit because tests are running!!");

            }else
            {
                Application.Exit();

            }
        }

        private void btnOpenFolderDialog_Click(object sender, EventArgs e)
        {
            DialogResult dlgResult = folderBrowserDialog1.ShowDialog();
            if(dlgResult==DialogResult.OK)
            {
                this.txtFolderName.Text = folderBrowserDialog1.SelectedPath;
            }

        }

        private void chkSelectAllNone_CheckedChanged(object sender, EventArgs e)
        {

            try
            {
                if (dataGridView1.Rows.Count > 0)
                {
                    bool checkedState = chkSelectAllNone.Checked;
                    foreach (DataGridViewRow itemRow in dataGridView1.Rows)
                    {
                        itemRow.Cells[3].Value = !checkedState;

                    }

                }
            }catch(Exception ex)
            {
                MessageBox.Show("An error ocurred.Try closing and re-opening the application.\n" + ex.Message);

            }


        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
           
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            
           


        }

        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {

            string testName = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            int totalTestRuns = 0;
            int totalTestRunsPassed = 0;
            int totalTestRunsFailed = 0;
            int totalTestRunsErrors = 0;
            
            List<pr_GetTestRunStatusCount_Result> listOfTestRunStatusCount=_data.GetTestRunStatusCount(testName).ToList();
            if (listOfTestRunStatusCount != null)
            {
                totalTestRuns = listOfTestRunStatusCount.Sum(item => Convert.ToInt32(item.Count));
            }
            string toolTip = "No execution of this test was done";
            if (totalTestRuns > 0)
            {
                toolTip = "Total Test Runs:" + totalTestRuns + "\n";
                
                totalTestRunsPassed = listOfTestRunStatusCount.Where(i => i.RunStatus == "Passed").Sum(item => Convert.ToInt32(item.Count));
                totalTestRunsFailed = listOfTestRunStatusCount.Where(i => i.RunStatus == "Failed").Sum(item => Convert.ToInt32(item.Count));
                totalTestRunsErrors = listOfTestRunStatusCount.Where(i => i.RunStatus == "Error").Sum(item => Convert.ToInt32(item.Count));
                toolTip += "Total Passed:" + totalTestRunsPassed + "\n";
                toolTip += "Total Failed:" + totalTestRunsFailed + "\n";
                toolTip += "Total Errors:" + totalTestRunsErrors + "\n";
               
            }
            dataGridView1.Rows[e.RowIndex].Cells[0].ToolTipText = toolTip;
        }

        private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            DBTestRecorder form = new DBTestRecorder();
            form.ShowDialog();
        }


        private void chTestCommandTime_GetToolTipText(object sender, ToolTipEventArgs e)
        {
            Chart cht = (Chart)sender;

            if (e.HitTestResult.ChartElementType == ChartElementType.DataPoint)
            {
                DataPoint obj = (DataPoint)e.HitTestResult.Object;
                e.Text = obj.YValues[0].ToString();

            }
        }

        

        private void chTestCommandTime_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            
            var pos = e.Location;

            var results = chTestCommandTime.HitTest(pos.X, pos.Y, false, ChartElementType.DataPoint);

            foreach (var result in results)
            {
                if (result.ChartElementType == ChartElementType.DataPoint)
                {
                    var series = result.Series;
                    var dataObject = result.Object as DataPoint;
                    string name = dataObject.AxisLabel;
                    string testStatus = "";
                    if(series!=null)
                    {
                        switch(series.Name.ToLower())
                        {
                            case "series1":
                                testStatus = "Passed";
                                break;
                            case "series2":
                                testStatus = "Failed";
                                break;
                            case "series3":
                                testStatus = "Error";
                                break;

                        }

                        ChartData data = new ChartData();
                        data.TestNameVar = name;
                        data.TestStatusVar = testStatus;
                        data.ShowDialog();

                    }
                    

                }


            }



        }

        private void button2_Click(object sender, EventArgs e)
        {
            _testLines = "~";
            int countToRun = 0;
            foreach (DataGridViewRow itemRow in dataGridView1.Rows)
            {
                bool canRun = itemRow.Cells[3].Value.ToString().ToLower() == "true";
                if (canRun)
                {
                    //itemRow.Cells[1].Value = "Running...";
                    string fileName = itemRow.Cells[0].Value.ToString();
                    string fullFileName = txtFolderName.Text + "\\" + fileName;
                    _testLines += "," + fullFileName;
                   
                    countToRun++;
                }


            }
            _testLines = _testLines.Replace("~,", "").Replace("~", "");

            if (string.IsNullOrEmpty(_testLines))
            {
                MessageBox.Show("A test file has not been selected!");
            }
            else
            {

                if (countToRun > 1)
                {
                    MessageBox.Show("You can only select one file at a time!");
                    return;
                }
                _createTestExe(_testLines);
                //do work here

            }
        }

        private void _onTestRunCompleteSimple(bool isPassed, string errorMessage)
        {

            Console.WriteLine("Complete-Error Messages:" + errorMessage);
        }
       private void _createTestExe(string fileFullPathAndName)
       {
           
           FileInfo sourceFile = new FileInfo(fileFullPathAndName);
           string directoryName = sourceFile.Name.Replace(".txt", "");
           string fullDirectoryName = sourceFile.Directory.FullName + "\\" + directoryName;
           if (!Directory.Exists(fullDirectoryName))
           {
               Directory.CreateDirectory(fullDirectoryName);
           }
           var files =new DirectoryInfo(fullDirectoryName).GetFiles();
           foreach (var file in files)
           {
               if (file.Extension == ".cs")
               {
                   file.Delete();
               }
               if (file.Extension == ".exe")
               {
                   file.Delete();
               }
           }

           //copy over required files into new directory
           string appDirectory = System.Environment.CurrentDirectory;
           var filesToCopy = new DirectoryInfo(appDirectory).GetFiles();
           foreach (var file in filesToCopy)
           {
               File.Copy(file.FullName, fullDirectoryName + "\\" + file.Name, true);
           }



           //string testFile = fileFullPathAndName;

           //String testLine = "";
           //string line = "";
           //using (StreamReader sr = new StreamReader(testFile))
           //{
           //    while ((line = sr.ReadLine()) != null)
           //    {
           //        testLine += line;
           //    }
           //}


           //string webAutoDllPath = System.Environment.CurrentDirectory + "\\WebAutomation.dll";
           //Assembly assembly = Assembly.LoadFrom(webAutoDllPath);
           //object obj = null;
           //var types = assembly.GetTypes();
           //Type typeInfo=null;
           //MethodInfo methodInfo = null;
           //MethodInfo methodInfo2 = null;
           //bool isFound = false;
           //foreach (var type in types)
           //{

           //    var methods = type.GetMethods();
           //    foreach (var method in methods)
           //    {
           //        var name = method.Name;
           //        if (name.ToLower().Contains("runtestnonthreaded"))
           //        {
           //            typeInfo = type;
           //            object[] parametersInstanceArray = new object[] { testLine, null };
           //            obj = Activator.CreateInstance(type, parametersInstanceArray);
           //            methodInfo = method;
           //            isFound = true;
           //            break;
           //        }

           //    }

           //    if (isFound)
           //    {
           //        break;
           //    }
           //}

           

           ////GetGlobaErrorMessage

           //object[] parametersArray = new object[] { null,0};
           //methodInfo.Invoke(obj, parametersArray);
           //methodInfo2 = typeInfo.GetMethod("GetGlobaErrorMessage");
           //string t = methodInfo2.Invoke(obj, null).ToString();

           string fullCSPathAndName = fullDirectoryName + "\\" + sourceFile.Name.Replace(".txt", ".cs");
           TextWriter writer = new StreamWriter(fullCSPathAndName);

           //we'll use the WriteLine() function to write all of our code
           writer.WriteLine("using System;");
           writer.WriteLine("using System.Collections.Generic;");
           //writer.WriteLine("using System.Drawing;");
           //writer.WriteLine("using System.Linq;");
           writer.WriteLine("using System.Runtime.InteropServices;");
           writer.WriteLine("using System.Threading;");
           //writer.WriteLine("using System.Windows.Documents;");
           //writer.WriteLine("using System.Windows.Forms;");
           //writer.WriteLine("using WebAuto.DataModel;");
           //writer.WriteLine("using WebAutomation;");
           writer.WriteLine("using System.IO;");
           writer.WriteLine("using System.Reflection;");
           writer.WriteLine("namespace WebAutoSingle");
           writer.WriteLine("{");
           writer.WriteLine("class Program");
           writer.WriteLine("{");
           writer.WriteLine("static void Main(string[] args)");
           writer.WriteLine("  {");
           writer.WriteLine("      string testFile =@\"" + fileFullPathAndName + "\";");
           writer.WriteLine("      string fileFullPathAndName =@\"" + fileFullPathAndName + "\";");
           writer.WriteLine("      String testLine = \"\";");
           writer.WriteLine("      String line = \"\";");
           writer.WriteLine("      using (StreamReader sr = new StreamReader(testFile))");
           writer.WriteLine("      {");
           writer.WriteLine("        while ((line = sr.ReadLine()) != null)");
           writer.WriteLine("        {");
           writer.WriteLine("           testLine+=line;");
           writer.WriteLine("        }");
           writer.WriteLine("      }");


           writer.WriteLine("      Console.WriteLine(\"******************Bunny Chow-Integration Tester v1.0.2*******************\");");
           writer.WriteLine("      Console.WriteLine(\"Started :\" + DateTime.Now);");
           writer.WriteLine("      Console.WriteLine(\"Press any key to start...\");");
           writer.WriteLine("      Console.ReadLine();");
           writer.WriteLine("      Console.WriteLine(\"Running test...please wait...\");");
           //writer.WriteLine("      Console.WriteLine(testLine);");
           writer.WriteLine("      Console.WriteLine(\"\");");
           //C:\Code\Dev\WebAutomation\WebAutomation\WebAutomation\bin\Debug
//           writer.WriteLine("      string webAutoDllPath = System.Environment.CurrentDirectory + @\"\\WebAutomation.dll\";");
           writer.WriteLine("      string webAutoDllPath =@\"C:\\Code\\Dev\\WebAutomation\\WebAutomation\\WebAutomation\\bin\\Debug\\WebAutomation.dll\";");
           writer.WriteLine("      Assembly assembly = Assembly.LoadFrom(webAutoDllPath);");
           writer.WriteLine("      object obj = null;");
           writer.WriteLine("      var types = assembly.GetTypes();");
           writer.WriteLine("      Type typeInfo = null;");
           writer.WriteLine("      MethodInfo methodInfo = null;");
           writer.WriteLine("      MethodInfo methodInfo2 = null;");
           writer.WriteLine("      bool isFound = false;");
           writer.WriteLine("      foreach(var type in types){");
           writer.WriteLine("       var methods = type.GetMethods();");
           writer.WriteLine("       foreach(var method in methods){");
           writer.WriteLine("         var name = method.Name;");
           writer.WriteLine("         if (name.ToLower().Contains(\"runtestnonthreaded\")){");
           writer.WriteLine("           typeInfo = type;");
           writer.WriteLine("           object[] parametersInstanceArray = new object[] { testLine,null };");
           writer.WriteLine("           obj = Activator.CreateInstance(type, parametersInstanceArray);");
           writer.WriteLine("           methodInfo = method;");
           writer.WriteLine("           isFound = true;");
           writer.WriteLine("           break;");
           writer.WriteLine("         }");
           writer.WriteLine("        if(isFound){break;}");
           writer.WriteLine("       }");
           writer.WriteLine("      }");
           //writer.WriteLine("     object[] parametersArray = new object[] { null, null, null, null, false, null, null,_onTestRunCompleteSimple };");
           writer.WriteLine("     object[] parametersArray = new object[] { null, 0};");
           writer.WriteLine("     methodInfo.Invoke(obj, parametersArray);");
           writer.WriteLine("     methodInfo2=typeInfo.GetMethod(\"GetGlobaErrorMessage\");");
           writer.WriteLine("     string msg=methodInfo2.Invoke(obj, null).ToString();");
           writer.WriteLine("     Console.WriteLine(\"Error Messages:\"+msg);");
           //writer.WriteLine("     methodInfo.Invoke(obj, parametersArray);");
           writer.WriteLine("     Console.WriteLine(\"Press any key to exit...\");");
           writer.WriteLine("     Console.ReadLine();");
           writer.WriteLine("  } ");

           writer.WriteLine("  private void _onTestRunCompleteSimple(bool isPassed,string errorMessage){");
           writer.WriteLine("   ");
           writer.WriteLine("      Console.WriteLine(\"Complete-Error Messages:\"+errorMessage);");
           writer.WriteLine("  } ");

           writer.WriteLine(" }");
           writer.WriteLine("}");
           writer.Close();



           _compileExecutable(fileFullPathAndName, fullCSPathAndName);

       }



       private static bool _compileExecutable(string testFile,String sourceName)
       {
           //Source file that you are compliling 
           FileInfo sourceFile = new FileInfo(sourceName);

           //Create a C# code provider 
           CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

           //Create a bool variable for to to use after the complie proccess to see if there are any erros
            bool compileOk = false;

             //Make a name for the exe
             String exeName = String.Format(@"{0}\{1}.exe",
             sourceFile.Directory, sourceFile.Name.Replace(".cs", ""));

             //Creates a variable, cp, to set the complier parameters
             CompilerParameters cp = new CompilerParameters();

             //You can generate a dll or a exe file, in this case we'll make an exe so we set this to true
             cp.GenerateExecutable = true;

             //Set the name
             cp.OutputAssembly = exeName;

             //Save the exe as a physical file
             cp.GenerateInMemory = false;

             //Set the compliere to not treat warranings as erros
             cp.TreatWarningsAsErrors = false;

             //Make it compile 
             CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);

             //if there are more then 0 erros...
             if (cr.Errors.Count > 0)
             {
                 //A message box shows the erros that occured 
                 MessageBox.Show("Errors building {0} into {1}" +
                     sourceName + cr.PathToAssembly);

                 //for each error that occured in the code make a separete message box
                 foreach (CompilerError ce in cr.Errors)
                 {
                     MessageBox.Show("  {0}" + ce.ToString());
                 }
             }

             //if there are no erros...
             else
             {
                 //a message box shows compliere results and a success message
                 MessageBox.Show("Source {0} built into {1} successfully." +
                     sourceName + cr.PathToAssembly);
                 //File.Delete(sourceFile.FullName);
             }

             //if there are erros...
             if (cr.Errors.Count > 0)
             {
                 //the bool variable that we made in the beggining is set to flase so the functions returns a false
                 compileOk = false;
             }

             //if there are no erros...
             else
             {
                 //we are returning a true (success)
                 compileOk = true;
             }

             //return the result
             return compileOk;
        }

       private void viewTestCommandsToolStripMenuItem_Click(object sender, EventArgs e)
       {
           AvailableCommands frmCommands = new AvailableCommands();
           frmCommands.ShowDialog();
       }

       private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
       {
           About frmAbout = new About();
           frmAbout.ShowDialog();
       }

       private void fAQToolStripMenuItem_Click(object sender, EventArgs e)
       {
           string FAQURL = ConfigurationManager.AppSettings["FAQURL"];
           ProcessStartInfo startInfo = new ProcessStartInfo("iexplore.exe");
           startInfo.Arguments = FAQURL;
           Process.Start(startInfo);
       }

       private void configurationEditorToolStripMenuItem_Click(object sender, EventArgs e)
       {
           AppConfigEditor appConfigFrm = new AppConfigEditor();
           appConfigFrm.ShowDialog();
       }



    }
}
